<template>
  <div class="follow-up-card">
    <div class="recording" :class="{ 'is-recording': isRecording }">
      <span>
        <span v-if="isRecording != 1">{{ formatTime(recordingTime) }}</span>
        <img
          src="@/assets/icon/Group.svg"
          alt=""
          style="vertical-align: sub; margin-left: 10px; cursor: pointer"
          @click="onToggleRecordingGroup"
          v-if="isRecording == 2"
        />
        <img
          src="@/assets/icon/icon_chongxin_nor.svg"
          alt=""
          style="vertical-align: sub; margin: 0 10px; cursor: pointer"
          @click="onToggleRecordingchongxin"
          v-if="isRecording == 3"
        />
        <img
          src="@/assets/icon/icon_xiazai_nor.svg"
          alt=""
          style="vertical-align: sub; margin-right: 10px; cursor: pointer"
          @click="onToggleRecordingxiazai"
          v-if="isRecording == 3"
        />
      </span>

      <span
        v-if="isRecording == 1"
        @click="onToggleRecording"
        style="cursor: pointer"
      >
        <img
          src="@/assets/icon/icon_kaishi_nor.svg"
          alt=""
          style="vertical-align: sub; margin-right: 6px; cursor: pointer"
        />开始录音</span
      >
    </div>
    <!-- 顶部tab切换栏 -->
    <div class="card-tabs">
      <div
        v-for="tab in tabs"
        :key="tab.value"
        class="card-title"
        :class="{ active: activeTab === tab.value }"
        @click="onActivated(tab.value)"
      >
        {{ tab.label }}{{ tab.count > 0 ? `(${tab.count})` : '' }}
      </div>
    </div>

    <!-- 折叠面板 -->
    <div v-if="historyList && historyList.length > 0">
      <el-collapse
        v-model="activeNames"
        class="follow-up-collapse"
        v-show="isExpanded"
        v-if="activeTab === 'history'"
        @change="toggleCollapse"
      >
        <el-collapse-item
          :name="item.medicalId"
          v-for="(item, index) in historyList"
          :key="item.medicalId"
        >
          <template #title>
            <div class="collapse-title">
              <span class="diagnosis">{{ item.diagnosis }}</span>
              <span class="diagnosis"
                >{{ item.doctorName
                }}{{ dayjs(item.visitDate).format('MM-DD') }}</span
              >
            </div>
          </template>
          <div
            style="
              display: flex;
              justify-content: space-between;
              margin-bottom: 10px;
            "
          >
            <div
              style="
                width: 115px;
                height: 22px;
                background: rgba(255, 255, 255, 0.4);
                border-radius: 3px 3px 3px 3px;
                border: 1px solid rgba(0, 0, 0, 0.1);
                text-align: center;
                cursor: pointer;
              "
              @click="onCopy(item)"
            >
              复制
            </div>
            <div
              style="
                width: 115px;
                height: 22px;
                background: rgba(255, 255, 255, 0.4);
                border-radius: 3px 3px 3px 3px;
                border: 1px solid rgba(0, 0, 0, 0.1);
                text-align: center;
                cursor: pointer;
              "
              @click="onPrint(item)"
            >
              打印
            </div>
          </div>
          <div style="border: 1px dashed #dcdcdc"></div>
          <div style="display: flex; justify-content: space-between">
            <span
              class="diagnosis"
              v-if="item.fieldList && item.fieldList.length != 0"
              >病历</span
            >
            <span
              style="color: #18b3ab; cursor: pointer"
              @click="onCopy1(item, '1')"
              v-if="item.fieldList && item.fieldList.length != 0"
              >复制</span
            >
          </div>
          <div
            class="collapse-content"
            v-for="(value, index) in item.fieldList"
            :key="index"
          >
            <div class="info-row">
              <span class="label"
                >{{ value.fieldName }}：{{ value.fieldValue }}</span
              >
            </div>
          </div>
          <div style="display: flex; justify-content: space-between">
            <span
              class="diagnosis"
              v-if="item.examList && item.examList.length != 0"
              >查验项目</span
            >
            <span
              style="color: #18b3ab; cursor: pointer"
              @click="onCopy1(item, '2')"
              v-if="item.examList && item.examList.length != 0"
              >复制</span
            >
          </div>
          <div
            class="collapse-content"
            v-for="(value, index) in item.examList"
            :key="index"
            style="margin-top: 5px"
          >
            <div class="info-row">
              <span
                class="label"
                style="display: flex; justify-content: space-between"
              >
                <span style="flex: 1 0 25%">{{ value.projectName }}</span>
                <span style="flex: 1 0 25%">
                  {{
                    useBaseDataStore.getEnumData(
                      value.projectCategory,
                      'projectCategoryEnum'
                    )
                  }}</span
                >
                <span style="flex: 1 0 25%">
                  {{ value.frequencyCodeText }}</span
                >
                <span style="flex: 1 0 25%">
                  {{ value.cycle }}{{ value.cycleUnitText }}
                </span>
                <!-- {{ value.remark }} -->
              </span>
            </div>
          </div>
          <div style="display: flex; justify-content: space-between">
            <span
              class="diagnosis"
              v-if="item.rxList && item.rxList.length != 0"
              >处方医嘱</span
            >
            <span
              @click="onCopy1(item, '3')"
              style="color: #18b3ab; cursor: pointer"
              v-if="item.rxList && item.rxList.length != 0"
              >复制</span
            >
          </div>
          <div
            class="collapse-content"
            v-for="(value, index) in item.rxList"
            :key="index"
          >
            <div v-if="value.rxType == '4'">
              <!-- <span class="label"></span> -->
              <div class="info-row">
                <span class="">
                  <div style="font-weight: 600">{{ value?.rxName }}</div>
                  <div style="margin-top: 5px">
                    <span> {{ value?.extInfo?.projectName }}</span>
                    <span style="margin-left: 10px">{{
                      value?.extInfo?.frequencyCodeText
                    }}</span>

                    <span style="margin-left: 10px">
                      {{ value?.extInfo?.cycle }}
                      {{
                        useBaseDataStore.getEnumData(
                          value?.extInfo?.cycleUnit,
                          'cycleUnitEnum'
                        )
                      }}</span
                    >

                    <span style="margin-left: 10px">
                      {{ value?.extInfo.remark }}</span
                    >

                    <span
                      style="
                        display: flex;
                        flex-wrap: wrap;
                        justify-content: flex-start;
                        align-items: flex-start;
                        margin-top: 5px;
                        gap: 3px;
                      "
                    >
                      <div
                        v-for="value1 in value?.extInfo.detailList"
                        style="flex: 0 0 32%; min-width: 0px; text-align: left"
                      >
                        <span>
                          {{
                            useBaseDataStore.getEnumData(
                              value1?.sideType,
                              'acupointSideTypeEnum'
                            )
                          }}
                          <span style="margin-left: 5px">{{
                            value1?.acupointName
                          }}</span>
                        </span>
                      </div>
                    </span>
                  </div>
                </span>
              </div>
            </div>
            <div v-if="value.rxType == '3'">
              <!-- <span class="label"></span> -->
              <div class="info-row">
                <span class="">
                  <div style="font-weight: 600">{{ value?.rxName }}</div>
                  <div style="margin-top: 5px">
                    <span>{{ value?.tcmInfo?.frequencyCodeText }}</span>
                    <span style="margin-left: 10px">
                      {{
                        useBaseDataStore.getEnumData(
                          value?.tcmInfo?.dailyDosage,
                          'tcmDailyDosageEnum'
                        )
                      }}
                    </span>
                    <span style="margin-left: 10px">
                      {{ value?.tcmInfo?.cycle }}
                      {{
                        useBaseDataStore.getEnumData(
                          value?.tcmInfo?.cycleUnit,
                          'cycleUnitEnum'
                        )
                      }}
                    </span>

                    <span style="margin-left: 10px">
                      {{ value?.tcmInfo.usageCodeText }}
                    </span>
                    <span style="margin-left: 10px">
                      {{ value?.tcmInfo?.singleDosage }}ml
                    </span>

                    <span style="margin-left: 10px">
                      {{ value?.tcmInfo.remark }}
                    </span>

                    <div
                      style="
                        display: flex;
                        flex-wrap: wrap;
                        justify-content: flex-start;
                        align-items: flex-start;
                        margin-top: 5px;
                        gap: 4px;
                      "
                    >
                      <div
                        v-for="value1 in value?.tcmInfo.detailList"
                        style="flex: 0 0 32%; min-width: 0; text-align: left"
                      >
                        <span>
                          {{ value1?.drugName }}
                          <span style="margin-left: 5px">
                            {{ value1?.dosage }}
                            {{ value1?.dosageUnitText }}</span
                          >
                        </span>
                      </div>
                    </div>
                  </div>
                </span>
              </div>
            </div>
            <div v-if="value.rxType == '2'">
              <!-- <span class="label"></span> -->
              <div class="info-row">
                <span class="">
                  <div style="font-weight: 600">{{ value?.rxName }}</div>
                  <div>
                    <div
                      v-for="value1 in value?.groupList"
                      style="margin-top: 5px"
                    >
                      <span> {{ value1?.groupName }}：</span>
                      <span style="margin-right: 10px">
                        {{ value1?.usageCodeText }}</span
                      >
                      <span style="margin-right: 10px">{{
                        value1?.frequencyCodeText
                      }}</span>
                      <span style="margin-right: 10px">
                        {{ value1?.cycle }} {{ value1?.cycleUnitText }}</span
                      >
                      <span style="margin-right: 10px"
                        >{{ value1?.ivDripRate }}滴/分钟</span
                      >
                      <div style="margin-top: 5px">
                        <div
                          v-for="value2 in value1?.detailList"
                          style="
                            margin-bottom: 5px;
                            display: flex;
                            flex-wrap: wrap;
                          "
                        >
                          <span
                            style="
                              margin-right: 10px;
                              display: block;
                              width: 122px;
                              overflow: hidden;
                              text-overflow: ellipsis;
                              white-space: nowrap;
                            "
                            >{{ value2?.drugName }}
                            <span v-if="value2.drugCategory == 3">
                              {{
                                value2.minPackQty +
                                value2.minPackUnitText +
                                '/' +
                                value2.packUnitText
                              }}
                            </span>
                            <span v-else>
                              {{
                                value2.drugDosage +
                                value2.drugDosageUnitText +
                                '*' +
                                value2.minPackQty +
                                value2.minPackUnitText +
                                '/' +
                                value2.packUnitText
                              }}
                            </span>
                          </span>

                          <span
                            style="
                              margin-right: 10px;
                              display: block;
                              width: 22px;
                            "
                          >
                            {{
                              useBaseDataStore.getEnumData(
                                value2.skinTest,
                                'skinTestEnum'
                              )
                            }}
                          </span>
                          <span style="margin-right: 10px">
                            {{ DrugCategoryEnumText(value2.drugCategory) }}
                          </span>
                          <span style="margin-right: 10px">
                            {{ value2?.dosage
                            }}{{ value2?.minPackUnitText }}</span
                          >

                          <span style="margin-right: 10px">
                            {{ value2.totalOutQty
                            }}{{ value2.totalOutQtyUnitText }}</span
                          >

                          <span style="margin-right: 10px">
                            {{ value2.remark }}</span
                          >
                        </div>
                      </div>
                    </div>
                  </div>
                </span>
              </div>
            </div>
            <div v-if="value.rxType == '1'">
              <!-- <span class="label"></span> -->
              <div class="info-row">
                <span class="">
                  <div style="font-weight: 600">{{ value?.rxName }}</div>
                  <div
                    v-for="value1 in value?.detailList"
                    style="margin-top: 5px; display: flex; flex-wrap: wrap"
                  >
                    <span
                      style="
                        margin-right: 10px;
                        display: block;
                        width: 122px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                      "
                    >
                      {{ value1?.drugName }}
                      <span v-if="value1.drugCategory == 3">
                        {{
                          value1.minPackQty +
                          value1.minPackUnitText +
                          '/' +
                          value1.packUnitText
                        }}
                      </span>
                      <span v-else>
                        {{
                          value1.drugDosage +
                          value1.drugDosageUnitText +
                          '*' +
                          value1.minPackQty +
                          value1.minPackUnitText +
                          '/' +
                          value1.packUnitText
                        }}
                      </span>
                    </span>
                    <span
                      style="margin-right: 10px; display: block; width: 22px"
                    >
                      {{ value1?.usageCodeText }}</span
                    >
                    <span
                      style="margin-right: 10px; display: block; width: 35px"
                    >
                      {{ value1?.frequencyCodeText }}</span
                    >
                    <span style="margin-right: 10px"
                      >{{ value1?.dosage }}{{ value1?.dosageUnitText }}</span
                    >
                    <span style="margin-right: 10px"
                      >{{ value1?.cycle }}{{ value1?.cycleUnitText }}</span
                    >
                    <span style="margin-right: 10px"
                      >{{ value1?.totalOutQty
                      }}{{ value1?.totalOutQtyUnitText }}</span
                    >
                    <span>{{ value1?.remark }}</span>
                  </div>
                </span>
              </div>
            </div>
          </div>
          <!-- 处方医嘱 -->
        </el-collapse-item>
      </el-collapse>
    </div>
    <div v-if="historyList.length == 0 && activeTab === 'history'">
      <el-empty :image-size="100" :image="emptyImage" description="暂无数据" />
    </div>
    <div v-if="activeTab === 'charge'">
      <!-- <report :historyList="historyList" /> -->
      <report :historyList="ExamHistory" />
      <div v-if="ExamHistory.length == 0">
        <el-empty
          :image-size="100"
          :image="emptyImage"
          description="暂无数据"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import emptyImage from '@/assets/icon/internet_empty_illustration.svg';
import { ref, watch, onMounted, onUnmounted } from 'vue';
import dayjs from 'dayjs';
import report from './report.vue';
import {
  getCheckRecordList,
  getDeptList,
  getMedicalDetail,
  getFollowupRecordList,
  getPatientHistoryCount,
  getPatientList,
} from '@/api/medical';
import stores from '@/store';

const useBaseDataStore = stores.useBaseDataStore();
const sideTypeEnum = ref<any>(
  stores.useBaseDataStore().getEnumSelect('acupointSideTypeEnum')
);
const DrugCategoryEnum = ref<any>(
  stores.useBaseDataStore().getEnumSelect('drugCategoryEnum')
);
const DrugCategoryEnumText = (val: string) => {
  return DrugCategoryEnum.value.find((item: any) => item.value === val)?.text;
};
const props = defineProps<{
  patientId: any;
  patientName: string;
}>();
const historyList = ref<any>([]);
const ExamHistory = ref<any>([]);

// 录音状态与资源
const isRecording = ref(1);
const mediaRecorder = ref<MediaRecorder | null>(null);
const mediaStream = ref<MediaStream | null>(null);
const audioChunks = ref<Blob[]>([]);
const recordingTime = ref(0);
const recordingInterval = ref<any>(null);
const emits = defineEmits(['onCopyIntm', 'onCopyIntm1', 'onPrint1']);
const mr = ref<MediaRecorder | null>(null);
const getBestAudioType = () => {
  // 优先使用 webm/opus（Chrome 支持好）
  const candidates = [
    { mimeType: 'audio/webm;codecs=opus', ext: 'webm' },
    { mimeType: 'audio/webm', ext: 'webm' },
    { mimeType: 'audio/ogg;codecs=opus', ext: 'ogg' },
    { mimeType: 'audio/ogg', ext: 'ogg' },
    { mimeType: 'audio/mp4', ext: 'm4a' },
  ];
  for (const c of candidates) {
    // @ts-ignore: isTypeSupported exists on MediaRecorder
    if (
      typeof MediaRecorder !== 'undefined' &&
      MediaRecorder.isTypeSupported?.(c.mimeType)
    ) {
      return c;
    }
  }
  return { mimeType: '', ext: 'webm' };
};

const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    mediaStream.value = stream;

    const { mimeType } = getBestAudioType();
    const options = mimeType ? { mimeType } : undefined;
    audioChunks.value = [];

    const mr = new MediaRecorder(stream, options);

    // 关键修复：设置时间片（每1秒触发一次）
    mr.start(1000); // 传入时间间隔参数

    mr.ondataavailable = (e: BlobEvent) => {
      if (e.data.size > 0) {
        audioChunks.value.push(e.data);
        //console.log('收到音频片段:', e.data.size, 'bytes');
      }
    };

    mediaRecorder.value = mr;
    isRecording.value = 2;

    // 计时逻辑保持不变
    recordingTime.value = 0;
    recordingInterval.value = window.setInterval(() => {
      recordingTime.value++;
    }, 1000);
  } catch (err) {
    //console.error('录音失败:', err);
    isRecording.value = 1;
  }
};
const onPrint = (item: any) => {
  //console.log('打印');
  emits('onPrint1', item);
};
// 添加: 暂停录音功能
const pauseRecording = () => {
  if (mediaRecorder.value && isRecording.value) {
    mediaRecorder.value.pause();
    isRecording.value = 3;
    // 停止计时器但不清零
    if (recordingInterval.value) {
      clearInterval(recordingInterval.value);
      recordingInterval.value = null;
    }
  }
};
// 复制
const onCopy = (item: any) => {
  //console.log('复制');
  emits('onCopyIntm', item);
};
const onToggleRecordingxiazai = async () => {
  if (audioChunks.value.length === 0) {
    //console.warn('没有录音数据可以下载');
    return;
  }
  //console.log(mediaRecorder.value);

  // 组装音频并自动下载
  const { ext, mimeType: mt } = getBestAudioType();
  const blob = new Blob(audioChunks.value, { type: mt || 'audio/webm' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `录音_${props.patientName}_${dayjs().format(
    'YYYY-MM-DD'
  )}.${ext}`;
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);

  // 释放流资源
  mediaStream.value?.getTracks().forEach((t) => t.stop());
  mediaStream.value = null;

  // 添加: 停止计时器
  if (recordingInterval.value) {
    clearInterval(recordingInterval.value);
    recordingInterval.value = null;
  }
  isRecording.value = 1;
  recordingTime.value = 0;
};
defineExpose<{
  onToggleRecordingxiazai: () => void;
  audioChunks: any;
}>({
  onToggleRecordingxiazai,
  audioChunks,
});
// 添加: 恢复录音功能
const resumeRecording = () => {
  if (mediaRecorder.value && !isRecording.value) {
    mediaRecorder.value.resume();
    isRecording.value = 3;

    // 恢复计时器
    if (!recordingInterval.value) {
      recordingInterval.value = window.setInterval(() => {
        recordingTime.value++;
      }, 1000);
    }
  }
};

const stopRecording = () => {
  if (mediaRecorder.value && isRecording.value) {
    try {
      mediaRecorder.value.stop();
    } catch (e) {
      //console.warn('停止录音时出现问题：', e);
    }
  }
  isRecording.value = 2;

  // 添加: 停止计时器
  if (recordingInterval.value) {
    clearInterval(recordingInterval.value);
    recordingInterval.value = null;
  }
};

// 添加: 格式化时间显示
const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, '0')}:${secs
    .toString()
    .padStart(2, '0')}`;
};
// 开始录音
const onToggleRecording = () => {
  startRecording();
  isRecording.value = 2;
};
const onToggleRecordingGroup = () => {
  // 如果正在录音，点击则暂停
  pauseRecording();
  isRecording.value = 3;
};
const onCopy1 = (item: any, type: any) => {
  //console.log('复制');
  emits('onCopyIntm1', item, type);
};
// 定义在组件顶层（假设使用Vue3 Composition API）
const audioPlayer = ref<HTMLAudioElement | null>(null);
const isPlaying = ref(false);
const playbackProgress = ref(0);
const volumeLevel = ref(0.7); // 默认音量70%

const onToggleRecordingchongxin = async () => {
  try {
    // 如果正在播放，则停止播放
    if (isPlaying.value) {
      audioPlayer.value?.pause();
      isPlaying.value = false;
      cleanupAudioResources(); // 清理资源
      return;
    }

    // 检查是否有可播放的数据
    if (audioChunks.value.length === 0) {
      //console.warn('没有可播放的录音数据');
      // 可以在这里添加UI提示
      return;
    }

    // 合并音频片段
    const { mimeType } = getBestAudioType();
    const blob = new Blob(audioChunks.value, {
      type: mimeType || 'audio/webm',
    });
    const audioUrl = URL.createObjectURL(blob);

    // 创建或复用audio元素
    if (!audioPlayer.value) {
      audioPlayer.value = new Audio();
      audioPlayer.value.loop = true; // 设置循环播放
      audioPlayer.value.volume = volumeLevel.value; // 设置默认音量

      // 添加进度监听
      audioPlayer.value.addEventListener('timeupdate', updatePlaybackProgress);

      // 播放结束处理
      audioPlayer.value.addEventListener('ended', () => {
        isPlaying.value = false;
      });

      // 错误处理
      audioPlayer.value.addEventListener('error', () => {
        if (audioPlayer.value?.error) {
          //console.error('播放错误:', audioPlayer.value.error);
        }
        isPlaying.value = false;
        cleanupAudioResources();
      });
    }

    // 设置音频源并播放
    audioPlayer.value.src = audioUrl;
    try {
      await audioPlayer.value.play();
      isPlaying.value = true;
    } catch (playErr) {
      // 处理自动播放被阻止的情况（如iOS限制）
      //console.error('播放被阻止:', playErr);
      isPlaying.value = false;
      cleanupAudioResources();
      // 可以在这里显示需要用户交互的提示
    }
  } catch (err) {
    //console.error('播放失败:', err);
    isPlaying.value = false;
    cleanupAudioResources();
  }
};

// 辅助方法：清理音频资源
const cleanupAudioResources = () => {
  if (audioPlayer.value) {
    // 移除事件监听器避免内存泄漏
    audioPlayer.value.removeEventListener('timeupdate', updatePlaybackProgress);
    audioPlayer.value.removeEventListener('ended', () => {});
    audioPlayer.value.removeEventListener('error', () => {});

    // 释放对象URL
    if (audioPlayer.value.src) {
      URL.revokeObjectURL(audioPlayer.value.src);
    }

    // 重置audio元素
    audioPlayer.value.src = '';
    audioPlayer.value = null;
  }
  playbackProgress.value = 0;
};

// 更新播放进度
const updatePlaybackProgress = () => {
  if (audioPlayer.value) {
    const progress =
      (audioPlayer.value.currentTime / audioPlayer.value.duration) * 100;
    playbackProgress.value = isNaN(progress) ? 0 : progress;
  }
};

// 音量控制
const setVolume = (volume: number) => {
  volumeLevel.value = Math.max(0, Math.min(1, volume));
  if (audioPlayer.value) {
    audioPlayer.value.volume = volumeLevel.value;
  }
};

const sideTypeEnumText = (val: any) => {
  for (let index = 0; index < sideTypeEnum.value.length; index++) {
    let item = sideTypeEnum.value[index];
    if (val == item.value) {
      return item.text;
    }
  }
};

const onActivated = async (value: string) => {
  activeTab.value = value;
  if (!props.patientId) {
    ExamHistory.value = [];
    return;
  }
  if (value === 'history') {
    getDeptListData();
  } else {
    ExamHistory.value = [];
    const data = await getCheckRecordList({
      patientId: props.patientId,
      pageNo: 1,
      pageSize: 10000,
    });
    if (data.code == '200') {
      ExamHistory.value = data.data;
    } else {
      ExamHistory.value = [];
      //ElMessage.error(data.msg);
    }
  }
  activeNames.value = '';
};
// const historyList = ref([
//   {
//     followupId: 6, //随访ID
//     visitNo: '20250801000920010', //诊号;唯一诊号
//     visitDate: '2025-08-01', //就诊日期yyyy-MM-dd
//     followupDate: '2025-08-04', //计划随访日期
//     followupStatus: '2', //随访状态 followupStatusEnum
//     realFollowupDate: '2025-08-04', //实际随访日期
//     followupEmpId: 10, //随访人ID
//     followupEmpName: '王医生的助理', //随访人姓名
//     followupResult: '无异常', //随访结果
//   },
//   {
//     followupId: 6, //随访ID
//     visitNo: '20250801000920010', //诊号;唯一诊号
//     visitDate: '2025-08-01', //就诊日期yyyy-MM-dd
//     followupDate: '2025-08-04', //计划随访日期
//     followupStatus: '2', //随访状态 followupStatusEnum
//     realFollowupDate: '2025-08-04', //实际随访日期
//     followupEmpId: 10, //随访人ID
//     followupEmpName: '王医生的助理', //随访人姓名
//     followupResult: '无异常', //随访结果
//   },
// ]);
// 顶部tab数据与选中状态
const tabs = ref<any>([
  {
    label: '历史',
    value: 'history',
    count: 0,
  },
  {
    label: '报告',
    value: 'charge',
    count: 0,
  },
]);
const activeTab = ref('history');

// 折叠面板控制
const activeNames = ref('');

const isExpanded = ref(true); // 控制折叠面板显示/隐藏
const getDeptListData = async () => {
  if (!props.patientId) {
    historyList.value = [];
    return;
  }
  const data = await getDeptList({
    patientId: props.patientId,
    pageNo: 1,
    pageSize: 10000,
  });

  if (data.code == '200') {
    historyList.value = data.data || [];
  } else {
    historyList.value = [];
    //ElMessage.error(data.msg);
  }
};
// 获取历史记录数量
const getRecordCount = async (id: any) => {
  if (!id) return (tabs.value[0].count = null);
  const data = await getPatientHistoryCount({
    patientId: id,
  });
  if (data.code == '200') {
    tabs.value[0].count = data.data;
  } else {
    //ElMessage.error(data.msg);
    return 0;
  }
};
// 获取检查报告数量
const getCheckRecordCount = async (id: any) => {
  if (!id) return (tabs.value[1].count = null);
  const data = await getPatientList({
    patientId: id,
    pageNo: 1,
    pageSize: 10000,
  });
  if (data.code == '200') {
    tabs.value[1].count = data.data;
  } else {
    //ElMessage.error(data.msg);
    return 0;
  }
};
watch(
  () => props.patientId,
  (val) => {
    // //console.log(val, 'historyList');
    activeTab.value = 'history';
    historyList.value = [];
    activeNames.value = '';
    // historyList.value = val;
    getDeptListData();
    getCheckRecordCount(props.patientId);
    getRecordCount(props.patientId);
    //console.log(val, 'ExamHistory');
  },
  { immediate: true, deep: true }
);

// 切换折叠状态
const toggleCollapse = async (event: any) => {
  // isExpanded.value = !isExpanded.value;
  //console.log('toggleCollapse', event);
  if (!event || event.length == 0 || !event[event.length - 1]) {
    return [];
  }
  const data = await getMedicalDetail({
    medicalId: event[event.length - 1],
  });
  if (data.code != '200') {
    //ElMessage.error(data.msg);
    return;
  }
  historyList.value = historyList.value.map((item: any) => {
    if (item.medicalId == event[event.length - 1]) {
      item = { ...item, ...data.data };
    }
    return item;
  });
  // //console.log(historyList.value);
};
onMounted(() => {});
onUnmounted(() => {
  try {
    if (isRecording.value) {
      stopRecording();
    }
    mediaStream.value?.getTracks().forEach((t) => t.stop());

    // 添加: 清理计时器
    if (recordingInterval.value) {
      clearInterval(recordingInterval.value);
      recordingInterval.value = null;
    }
  } catch {}
});
</script>

<style scoped lang="scss">
.follow-up-card {
  border-radius: 8px;
  width: 280px;
  height: 100%;
  overflow: auto;
}

.card-tabs {
  display: flex;
  width: 100%;
  background: rgba(253, 253, 253, 0.6);
  border-radius: 8px 8px 0 0;
  border-bottom: 1px solid #ededed;
}
.card-title {
  flex: 1;
  text-align: center;
  height: 48px;
  line-height: 48px;
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  color: #999;
  background: transparent;
  transition: color 0.2s, background 0.2s;
}
.card-title.active {
  color: #222;
  font-weight: 700;
}

.diagnosis-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e7e7e7;
}

.diagnosis-name {
  font-size: 16px;
  color: #666;
}

.doctor-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: opacity 0.2s ease;
}

.doctor-info:hover {
  opacity: 0.8;
}

.doctor-name {
  font-size: 14px;
  color: #666;
}

.visit-date {
  font-size: 14px;
  color: #666;
}

.expand-icon {
  font-size: 12px;
  color: #666;
  transition: transform 0.3s ease;
}

.expand-icon.rotated {
  transform: rotate(180deg);
}

.follow-up-collapse {
  border: none;
  // padding: 0px 16px 10px 16px;
}
::v-deep(.el-collapse-item__wrap) {
  padding: 10px;
}
:deep(.el-collapse-item__header) {
  border: none;
  padding: 0px 8px;
}

:deep(.el-collapse-item__arrow) {
  transition: transform 0.3s ease;
  transform: rotate(-90deg); /* 默认状态(关闭时)向上 */
}

:deep(.el-collapse-item__arrow.is-active) {
  transform: rotate(90deg); /* 展开状态(打开时)向下 */
}

:deep(.el-collapse-item__content) {
  padding: 16px 8px 16px 8px;
  background: #f8f8f8;
  border-radius: 0 0 6px 6px;
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #dcdcdc;
}

.collapse-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.diagnosis {
  color: #333;
  font-weight: bold;
  font-size: 13px;
}

.action-btn {
  font-size: 14px;
  color: #00b3b3;
  cursor: pointer;
}

.collapse-content {
  font-size: 11px;
  line-height: 1.6;
}

.info-row {
  margin-bottom: 8px;
}

.label {
  color: #666;
  min-width: 80px;
  flex-shrink: 0;
}

.value {
  color: #333;
  flex: 1;
}
.tcm-box {
  display: flex;
  flex-wrap: wrap;
  border-bottom: 1px dashed #dcdcdc;
  gap: 0;
}
.tcm-box .info-row {
  width: 33.33%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 0;
  padding: 8px 0;
}
.tcm-box .label {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
}
.recording {
  font-size: 14px;
  width: 280px;
  height: 40px;
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #dcdcdc;
  font-weight: 400;
  font-size: 14px;
  color: #16ada4;
  text-align: center;
  line-height: 40px;
  overflow: hidden;
  margin-top: 10px;
  margin-bottom: 10px;
  user-select: none;
}
// .recording.is-recording {
//   border-color: #f56c6c;
//   color: #f56c6c;
// }
</style>
